import React, { Component } from "react";
import _ from "lodash";
import "../assest/css/todoList.css";

export default class todoList extends Component {
  myinput = React.createRef();

  state = {
    demoList: [
      { id: 1, value: "我艹1" },
      { id: 2, value: "我艹2" },
      { id: 3, value: "我艹3" },
    ],
  };
  render() {
    let newList = this.state.demoList.map((item, index) => (
      <div key={item.id} className="list-item">
        {index + 1} 、{/* {item.value} */}
        {/* 富文本插入，html元素 */}
        <span dangerouslySetInnerHTML={{ __html: item.value }}></span>
        <button
          className="btn del-btn"
          onClick={this.delItem.bind(this, item.id)}>
          删除
        </button>
      </div>
    ));
    return (
      <div>
        <input type="text" ref={this.myinput} />
        <button onClick={this.handleClick} className="btn add-btn">
          新增任务
        </button>
        <div>{newList}</div>
        <span className={this.state.demoList.length !== 0 ? "hidden" : ""}>
          暂无代办事件
        </span>
      </div>
    );
  }

  handleClick = () => {
    // 一般不直接修改state数据，可以深拷贝一份进行操作，最后再赋值给state
    let newList = _.cloneDeep(this.state.demoList);
    newList.push({
      id: Math.random() * 10,
      value: this.myinput.current.value,
    });
    this.setState({
      demoList: newList,
    });
    this.myinput.current.value = "";
  };
  delItem(id) {
    let newList = _.cloneDeep(this.state.demoList);
    newList.forEach((item, index) => {
      if (item.id === id) {
        newList.splice(index, 1);
      }
    });
    this.setState({
      demoList: newList,
    });
  }
}
